import { HttpException, Injectable } from '@nestjs/common';
import { InjectEntityManager } from '@nestjs/typeorm';
import { EntityManager } from 'typeorm';
import { User } from './entities/user.entity';
import { RegisterDto } from './dto/register.dto';
import * as crypto from 'crypto';
import { LoginDto } from './dto/login.dto';
import { Permission } from './entities/permission.entity';

function md5(str) {
  const hash = crypto.createHash('md5');
  hash.update(str);
  return hash.digest('hex');
}

@Injectable()
export class UserService {

  @InjectEntityManager()
  private manager: EntityManager;

  // 获取uuid
  getUUid (): string {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
  }

  async findUserById(id: number) {
    return await this.manager.findOne(User, {
        where: { id }
    });
  }


  // 获取用户信息
  async findOne(username: string) {
    const user = await this.manager.findOne(User, {
      where: { username }
    })
    return user;
  }

  // 通过用户名查找
  async findByUsername(username: string) {
    const user = await this.manager.findOne(User, {
      where: {
        username,
      },
      relations: {
        permissions: true
      }
    });
    return user;
  }  

  // 新增用户
  async add(data: object) {
    return await this.manager.save(User, {
      ...data
    })
  }

  // 注册用户
  async register(user: RegisterDto) {
    const foundUser = await this.manager.findOne(User, {
      where: { username: user.username }
    });

    if(foundUser) {
      throw new HttpException('用户已存在', 200);
    }

    const newUser = new User();
    newUser.username = user.username;
    newUser.password = md5(user.password);

    try {
      await this.manager.save(User, {
        ...newUser
      });
      return true;
    } catch(e) {
      return false;
    }
  }

  async login(user: LoginDto) {
    const foundUser = await this.manager.findOne(User, {
     where: {username: user.username}
    });

    if(!foundUser) {
      throw new HttpException('用户名不存在', 200);
    }
    if(foundUser.password !== md5(user.password)) {
      throw new HttpException('密码错误', 200);
    }
    return foundUser;
  }

  // 初始化关联user 和 permission 的数据
  async initData() {
    const permission1 = new Permission();
    permission1.name = 'create_aaa';
    permission1.desc = '新增 aaa';

    const permission2 = new Permission();
    permission2.name = 'update_aaa';
    permission2.desc = '修改 aaa';

    const permission3 = new Permission();
    permission3.name = 'remove_aaa';
    permission3.desc = '删除 aaa';

    const permission4 = new Permission();
    permission4.name = 'query_aaa';
    permission4.desc = '查询 aaa';

    const permission5 = new Permission();
    permission5.name = 'create_bbb';
    permission5.desc = '新增 bbb';

    const permission6 = new Permission();
    permission6.name = 'update_bbb';
    permission6.desc = '修改 bbb';

    const permission7 = new Permission();
    permission7.name = 'remove_bbb';
    permission7.desc = '删除 bbb';

    const permission8 = new Permission();
    permission8.name = 'query_bbb';
    permission8.desc = '查询 bbb';

    const user1 = new User();
    const password1 = '123456';
    user1.username = '东东';
    user1.password = md5(password1);
    user1.permissions  = [
      permission1, permission2, permission3, permission4
    ]

    const user2 = new User();
    const password2 = '123456';
    user2.username = '光光';
    user2.password = md5(password2);
    user2.permissions  = [
      permission5, permission6, permission7, permission8
    ]

    await this.manager.save([
      permission1, 
      permission2,
      permission3,
      permission4,
      permission5,
      permission6,
      permission7,
      permission8
    ])
    await this.manager.save([
      user1, 
      user2
    ]);
  }
}
